using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Mes.Processes.StepMaterials.Commands;

/// <summary>
/// 工序物料更新命令。
/// </summary>
public sealed record UpdateStepMaterialCommand(long Id, ProcStepMaterialDto StepMaterial) : IRequest<IResult<bool>>;

internal sealed class UpdateStepMaterialCommandHandler(IRepository<ProcStepMaterial> repo) : IRequestHandler<UpdateStepMaterialCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateStepMaterialCommand request, CancellationToken cancellationToken)
    {
        var steMaterial = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (steMaterial == null)
        {
            return Result.Failure("未找到要更新的工艺物料");
        }

        steMaterial.MaterialId = request.StepMaterial.MaterialId;
        steMaterial.Qty = request.StepMaterial.Qty;
        steMaterial.Seq = request.StepMaterial.Seq;
        steMaterial.IsCheckSource = request.StepMaterial.IsCheckSource;
        steMaterial.SourceLineIds = request.StepMaterial.SourceLineIds;

        var ok = await repo.UpdateAsync(steMaterial, m => new
        {
            m.MaterialId,
            m.Qty,
            m.Seq,
            m.IsCheckSource,
            m.SourceLineIds,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
